﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Net.Http;

using CloudSoft.Workflows;

using CloudSoft.Extensions;

namespace ERPStore.Exporter.Workflows.Activities
{

	public sealed class GenerateShopzillaTaxonomy : CodeActivity
	{
		protected override void Execute(CodeActivityContext context)
		{
			var result = new List<Models.ShopzillaCategory>();
			string content = null;
			var httpClient = new HttpClient();
			string url = "http://merchant.shopzilla.fr/oa/general/taxonomy.xpml";
			var task = httpClient.GetByteArrayAsync(url).ContinueWith((response) =>
				{
					var buffer = response.Result;
					content = System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length);

					if (content == null)
					{
						return;
					}

					var regexp = new System.Text.RegularExpressions.Regex(@"<td\s+height=""30""\s+style="".*?"">(?<category>.+)</td>", System.Text.RegularExpressions.RegexOptions.Multiline);

					System.Text.RegularExpressions.Match m;
					bool createCategory = true;
					Models.ShopzillaCategory category = null;
					for (m = regexp.Match(content); m.Success; m = m.NextMatch())
					{
						var value = m.Groups["category"].Value;
						if (createCategory)
						{
							category = new Models.ShopzillaCategory();
							category.Name = System.Web.HttpUtility.HtmlDecode(value);
							createCategory = false;
						}
						else
						{
							category.Code = value.Replace(".", "");
							result.Add(category);
							createCategory = true;
						}
					}
				}).Wait(30 * 1000); // Attendre 30s maxi

			var cacheService = context.GetService<ERPStore.Services.ICacheService>();
			cacheService.Add("ShopzillaCategoryList", result, DateTime.Now.AddDays(1));

			if (!result.IsNullOrEmpty())
			{
				var path = Configuration.ConfigurationSettings.AppSettings["exportPath"];
				var configFileName = string.Format("{0}", System.IO.Path.Combine(path, "shopzilla.taxonomy.xml"));
				var serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<Models.ShopzillaCategory>));
				using (var fs = System.IO.File.OpenWrite(configFileName))
				{
					serializer.Serialize(fs, result);
					fs.Flush();
				}
			}

		}
	}
}
